package com.aios.action.door;

import java.util.List;

import com.aios.service.ExistValidationEnum;

public class DoorSaveAction extends AbstractDoorAction {

	private static final long serialVersionUID = 1L;
	private List<Integer> selectedUserList;
	private List<Integer> selectedGroupList;

	public String execute() {
		commonValidation();
		if (hasErrors()) {
			return INPUT;
		}

		try {
			if (this.mode == Mode.ADD) {
				ExistValidationEnum existValidationEnum = doorService
						.validateDoorName(door.getDoorName());

				if (existValidationEnum != ExistValidationEnum.NOT_EXIST) {
					addActionError(getText("door.name.exist"));
					inputPopulate();
					return INPUT;
				}
				doorService.save(door, getSessionUserVariable().getId());
				door.setId(doorService.findIdByDoorName(door.getDoorName()));
				doorService.saveUserList(door, selectedUserList,
						getSessionUserVariable().getId());
				doorService.saveGroupList(door, selectedGroupList,
						getSessionUserVariable().getId());
			} else {
				ExistValidationEnum existValidationEnum = doorService
						.validateDoorName(door.getDoorName(),door.getId());

				if (existValidationEnum != ExistValidationEnum.NOT_EXIST) {
					addActionError(getText("door.name.exist"));
					editPopulate();
					return INPUT;
				}
				doorService.update(door, getSessionUserVariable().getId());
				doorService.updateUserList(door, selectedUserList,
						getSessionUserVariable().getId());
				doorService.updateGroupList(door, selectedGroupList,
						getSessionUserVariable().getId());
			}
		} catch (Exception e) {
			// logger
			addActionError(getText("door.add.error"));
			inputPopulate();
			return INPUT;
		}

		return SUCCESS;
	}

	private void commonValidation() {

		if (door.getDoorName().isEmpty()) {
			addFieldError("door.doorName", getText("error.door.name.empty"));
		}

		if (this.mode == Mode.ADD) {
			addValidation();
		} else if (this.mode == Mode.EDIT) {
			editValidation();
		} else {

		}
	}

	private void addValidation() {
		if (door.getId() != null) {
			addActionError("door.error.id.exist");
		}
	}

	private void editValidation() {
		if (door.getId() == null) {
			addActionError("door.error.id.not.exist");
		}
	}

	public List<Integer> getSelectedUserList() {
		return selectedUserList;
	}

	public void setSelectedUserList(List<Integer> selectedUserList) {
		this.selectedUserList = selectedUserList;
	}

	public List<Integer> getSelectedGroupList() {
		return selectedGroupList;
	}

	public void setSelectedGroupList(List<Integer> selectedGroupList) {
		this.selectedGroupList = selectedGroupList;
	}

}
